package ar.republicagroup.gestion.view;


import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.Deposito;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.DepositoServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class frmDepositoEfectivo extends javax.swing.JFrame {

    private static frmDepositoEfectivo instance;
    /* Services */
   ClienteServices clienteServices           = (ClienteServices)SpringUtils.getBean("clienteServices");
   DepositoServices    depositoServices      = (DepositoServices)SpringUtils.getBean("depositoServices");
   /*List*/
   List<Deposito> depositoList              = new ArrayList<>();
   /* Logging */
   private static Logger log = Logger.getLogger(frmDepositoEfectivo.class);
   
    private frmDepositoEfectivo() {
        initComponents();
        valoresPorDefecto();
        cargarCombos();
    }

    public static frmDepositoEfectivo getInstance(){
        if(instance==null){
            instance = new frmDepositoEfectivo();
        }
    
        return instance;
    }
    
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        btnNuevoDeposito = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();
        btnLiquidar = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        comboClientes = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        btnBuscar = new javax.swing.JButton();
        calendarDesde = new com.toedter.calendar.JDateChooser();
        calendarHasta = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        rbtLiquidados = new javax.swing.JRadioButton();
        rbtPendientes = new javax.swing.JRadioButton();
        rbtVerTodo = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblDepositos = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnNuevoDeposito.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnNuevoDeposito.setText("Nuevo depósito");
        btnNuevoDeposito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoDepositoActionPerformed(evt);
            }
        });

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/edit.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.setEnabled(false);
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnActualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/update.png"))); // NOI18N
        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        btnLiquidar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/payment_icon.png"))); // NOI18N
        btnLiquidar.setText("Liquidar");
        btnLiquidar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLiquidarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNuevoDeposito)
                .addGap(18, 18, 18)
                .addComponent(btnModificar)
                .addGap(18, 18, 18)
                .addComponent(btnActualizar)
                .addGap(18, 18, 18)
                .addComponent(btnLiquidar)
                .addContainerGap(35, Short.MAX_VALUE))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnActualizar, btnLiquidar, btnModificar, btnNuevoDeposito});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNuevoDeposito)
                    .addComponent(btnModificar)
                    .addComponent(btnActualizar)
                    .addComponent(btnLiquidar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setPreferredSize(new java.awt.Dimension(800, 426));

        jLabel2.setText("Cliente");

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/search.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        jLabel3.setText("Desde");

        jLabel4.setText("Hasta");

        buttonGroup1.add(rbtLiquidados);
        rbtLiquidados.setText("Liquidados");

        buttonGroup1.add(rbtPendientes);
        rbtPendientes.setText("Pendientes");

        buttonGroup1.add(rbtVerTodo);
        rbtVerTodo.setText("Ver todo");

        jLabel5.setText("Ver");

        tblDepositos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Fecha depósito", "Cliente", "Comisión efectivo", "Efectivo depositado", "Cta. Bancaria", "Fecha liquidación"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblDepositos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane2.setViewportView(tblDepositos);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel4Layout.createSequentialGroup()
                                        .addComponent(rbtLiquidados)
                                        .addGap(22, 22, 22)
                                        .addComponent(rbtPendientes))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                                        .addComponent(calendarDesde, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel4)))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel4Layout.createSequentialGroup()
                                        .addComponent(rbtVerTodo)
                                        .addGap(18, 18, 18)
                                        .addComponent(btnBuscar))
                                    .addComponent(calendarHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
                    .addComponent(jSeparator1))
                .addContainerGap(258, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(calendarHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(calendarDesde, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbtLiquidados)
                    .addComponent(rbtPendientes)
                    .addComponent(rbtVerTodo)
                    .addComponent(jLabel5)
                    .addComponent(btnBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Buscar depósitos", jPanel4);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 843, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(69, 69, 69))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 634, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 10, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLiquidarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLiquidarActionPerformed
        int[] indicesSelected = tblDepositos.getSelectedRows();
        List<Deposito> depositoList = new ArrayList<>();
        
        if(indicesSelected.length > 0){
        
            for (int i = 0; i < indicesSelected.length; i++) {
                int j = indicesSelected[i];
                Deposito deposito = (Deposito)tblDepositos.getValueAt(j, 0);

                if(deposito.getFechaLiquidacion() == null){
                    depositoList.add(deposito);
                }
            }
            
            if(!depositoList.isEmpty()){
                modalPanelAddLiquidacionDeposito panelDeposito = new modalPanelAddLiquidacionDeposito(this, true);
                panelDeposito.setDepositoList(depositoList);
                UserInterfaceHelper.centreWindow(panelDeposito);
                panelDeposito.setVisible(true);
            }else{
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("depositosLiquidados"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }
        }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedLiquidacion"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnLiquidarActionPerformed

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        buscarDepositos();
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void btnNuevoDepositoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoDepositoActionPerformed
        frmAddDepositoEfectivo formulario = frmAddDepositoEfectivo.getInstance();
        formulario.setVisible(true);
    }//GEN-LAST:event_btnNuevoDepositoActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
       if(comboClientes.getSelectedIndex() > 0){ 
            buscarDepositos();
       }else{
           JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
       }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        
        if(tblDepositos.getSelectedRow() != -1){
            Deposito deposito                   = (Deposito)tblDepositos.getValueAt(tblDepositos.getSelectedRow(), 0);
            frmEditDepositoEfectivo  formulario = frmEditDepositoEfectivo.getInstance(); 
            formulario.setDepositoToEdit(deposito);
            UserInterfaceHelper.centreWindow(this);
            formulario.setVisible(true);
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void buscarDepositos(){
       
        int radioButtonOption = 0;
        
        if(rbtLiquidados.isSelected()){
              radioButtonOption = DepositoServices.OPTION_LIQUIDADOS;
          }else if (rbtPendientes.isSelected()){
              radioButtonOption = DepositoServices.OPTION_PENDIENTES;
          }else {
              radioButtonOption = DepositoServices.OPTION_VERTODO;
          }
        
        Cliente cliente = null;
        
        if(comboClientes.getSelectedIndex() > 0){
            JComboBoxModel model    =(JComboBoxModel)comboClientes.getSelectedItem();
            cliente         = clienteServices.get(Integer.parseInt(model.getValue()));
        } 
        
        depositoList = depositoServices.getDepositosByFilters(cliente,calendarDesde.getDate(),calendarHasta.getDate(),radioButtonOption);
        cargarTablaDeposito(depositoList);
    }
    
    
    
    
    private void cargarCombos(){
         comboClientes.setModel(clienteServices.combo());
    }
    
    private void valoresPorDefecto(){
         UserInterfaceHelper.setJFrameIconImage(this);
         UserInterfaceHelper.centreWindow(this);
         UserInterfaceHelper.setTitleToThisJFrame(this, "Depósitos en efectivo");
         rbtVerTodo.setSelected(true);
         calendarDesde.setDate(new Date());
         calendarHasta.setDate(new Date());
        
    }
    
    public static void cargarTablaDeposito(List<Deposito> depositoList){
        try{
            DefaultTableModel model = (DefaultTableModel) tblDepositos.getModel();
            model.getDataVector().clear();
            for(Deposito deposito : depositoList){
               model.addRow(new Object[]{ deposito,Formato.fechaDDMMYY(deposito.getFechaDeposito()),deposito.getClienteId().getNombre(),deposito.getComision().doubleValue(),Formato.decimalComaMilesConSigno(deposito.getEfectivoDepositado().doubleValue()),deposito.getCuentaBancoId().getNombre(),Formato.fechaDDMMYY(deposito.getFechaLiquidacion())});
            }
        
            TableColumnAdjuster tca = new TableColumnAdjuster(tblDepositos);
            tca.adjustColumns();
            tblDepositos.setModel(model);
            tblDepositos.repaint();
        }catch(Exception ex){
           log.error(ex.getMessage(),ex);
        }
    }
    
  public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmDepositoEfectivo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected static javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnLiquidar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnNuevoDeposito;
    private javax.swing.ButtonGroup buttonGroup1;
    private com.toedter.calendar.JDateChooser calendarDesde;
    private com.toedter.calendar.JDateChooser calendarHasta;
    private javax.swing.JComboBox comboClientes;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JRadioButton rbtLiquidados;
    private javax.swing.JRadioButton rbtPendientes;
    private javax.swing.JRadioButton rbtVerTodo;
    protected static javax.swing.JTable tblDepositos;
    // End of variables declaration//GEN-END:variables
}
